package homework.qingming.calc.functions;

import homework.qingming.calc.Executable;

import java.math.BigDecimal;
import java.security.InvalidParameterException;

public abstract class BaseFunction implements Executable {

    private String funcName;
    private int maxParamsLen;
    private int minParamsLen;

    public BaseFunction(String name, int len) {
        this(name, len, len);
    }

    public BaseFunction(String name, int minParLen, int maxParLen) {
        if(!name.matches("[a-zA-z]+")) {
            throw new InvalidParameterException("函数名只能包含字母: "+name);
        }
        funcName = name;
        minParamsLen = minParLen;
        maxParamsLen = maxParLen;
    }

    public String getFuncName() {
        return funcName;
    }

    public abstract BigDecimal function(BigDecimal... v);

    @Override
    public BigDecimal exec(BigDecimal... v) {
        if(!checkParamsLength(v.length))
            throw new UnsupportedOperationException(funcName+"函数参数过多");
        return function(v);
    }

    @Override
    public boolean checkParamsLength(int len) {
        return len >= minParamsLen && len <= maxParamsLen;
    }

    @Override
    public int getPriority() {
        return Integer.MAX_VALUE;
    }

    @Override
    public String toString() {
        return funcName;
    }
}
